import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutterlib/common/constants/constants.dart';
import 'package:flutterlib/common/net/retrofit/post_api.dart';
import 'package:flutterlib/common/utils/toast.dart';
import 'package:flutterlib/common/utils/utils.dart';
import 'package:flutterlib/model/interest/interest_bean.dart';
import 'package:flutterlib/model/post/post_bean.dart';
import 'package:flutterlib/pages/post/viewmodel/post_store.dart';
import 'package:flutterlib/widgets/bussiness/user_info_widget.dart';
import 'package:flutterlib/widgets/dialog/heart_dialog.dart';
import 'package:flutterlib/widgets/tcard/cards.dart';
import 'package:flutterlib/widgets/tcard/swip_info.dart';
import 'package:loading/indicator/ball_beat_indicator.dart';
import 'package:loading/loading.dart';
import 'package:mobx/mobx.dart';
import 'package:smart_select/smart_select.dart';

//用于加载内部继承上下拉的页面state的外部容器页面，
//适用于带tabbar，内部是list的页面的改造
class Page extends StatefulWidget {
  Page({Key key}) : super(key: key);

  @override
  PageState createState() => PageState();
}

class PageState extends State<Page> with SingleTickerProviderStateMixin {
  static const int CARD_SIZE = 30;
  TCardController _controller = TCardController();
  PostStore postStore = PostStore();
  int page = 0;
  List<Widget> cards = <Widget>[];
  List<PostBean> cardBeans = [];
  int _index = 0;
  InterestBean interest;

  @override
  void initState() {
    super.initState();
    postStore.fetchCards(page, CARD_SIZE, "createTime,desc", interest == null ? 0 : interest.id);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: QuhuiColors.mainBackgroundColor,
        title: Text("趣图", style: QuhuiConstant.normalTextBold),
        leading: MyBackButton(
          color: Colors.black,
        ),
      ),
      body: Column(
        children: [
          Observer(
            builder: (_) {
              var cardPageFuture = postStore.cardPageFuture;
              switch (cardPageFuture.status) {
                case FutureStatus.fulfilled:
                  if (cards.length == 0) {
                    addCardsFromData(cardPageFuture.value.content);
                  }
                  return buildTCard();
                default:
                  return Center(
                    child: Text("加载中..", style: QuhuiConstant.middleTextBold,),
                  );
              }
            },
          ),
          Observer(builder: (_) {
                          List<InterestBean> result = allInterestsFromSP;
                          InterestBean bean = InterestBean(id: 0, name: '全部');
                          result.insert(0, bean);
                          var choice = result
                              .map((e) => S2Choice<InterestBean>(
                                  value: e, title: e.name))
                              .toList();
                          return SmartSelect<InterestBean>.single(
                            title: '选择兴趣',
                            value: interest,
                            placeholder: '',
                            choiceItems: choice,
                            onChange: (state){
                              interest = state.value;
                              cards.clear();
                              postStore.fetchCards(page, CARD_SIZE, "createTime,desc", interest == null ? 0 : interest.id);
                            },
                            modalType: S2ModalType.bottomSheet,
                            modalFilter: true,
                            tileBuilder: (context, state) {
                              return S2Tile.fromState(
                                state,
                                isTwoLine: false,
                              );
                            },
                          );
                        }),
        ],
      ),
    );
  }

  Widget buildTCard() {
    return Column(
      children: <Widget>[
        Text(
          "左滑喜欢，右滑不喜欢，相互喜欢会自动加好友",
          style: QuhuiConstant.minSubText,
        ),
        TCard(
          size: Size(400.h, MediaQuery.of(context).size.height/3*2),
          cards: cards,
          controller: _controller,
          onForward: (index, info) async {
            _index = index;
            trueDebugPrint("card index $_index");
            if (info.direction == SwipDirection.Left) {
              PostApi.builder().likeCard(cardBeans[index - 1].id).then((value) {
                if (value != null && value.match) {
                  var userName = cardBeans[index - 1].userName;
                  HeartDialog.show(
                    context,
                    text: '与${userName}加为好友',
                  );
                  // ToastUtils.success("与${userName}加为好友");
                }
              });
            } else {
              PostApi.builder().unLikeCard(cardBeans[index - 1].id);
            }
            if (index == cards.length - 5) {
              page++;
              var pageByQuerySheet = await PostApi.builder().pageByQuerySheet(
                  page, CARD_SIZE, "createTime desc", interest == null ? 0 : interest.id);
              addCardsFromData(pageByQuerySheet.content);
            }
            setState(() {});
          },
          onBack: (index) {
            _index = index;
            setState(() {});
          },
          onEnd: () {
            print('end');
          },
        ),
        SizedBox(height: 20),
      ],
    );
  }

  void addCardsFromData(List<PostBean> content) {
    List<Widget> list = List.generate(
      content.length,
      (int index) {
        PostBean cardBean = content[index];
        return Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16.0),
            boxShadow: [
              BoxShadow(
                offset: Offset(0, 17),
                blurRadius: 23.0,
                spreadRadius: -13.0,
                color: Colors.black54,
              )
            ],
          ),
          child: Stack(
            fit: StackFit.expand,
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(16.0),
                child: Image.network(
                  cardBean.thumbnail,
                  fit: BoxFit.cover,
                ),
              ),
              Positioned(
                width: MediaQuery.of(context).size.width,
                top: 0,
                child: ClipRRect(
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Container(
                      height: 80,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              UserInfoWidget(
                                width: 33,
                                height: 33,
                                image: cardBean.userLogo,
                                onPressed: () {
                                  NavigatorUtils.goUserHome(
                                      context, cardBean.userId);
                                },
                              ),
                              Text(
                                cardBean.userName,
                                style: QuhuiConstant.smallTextBold,
                              ),
                            ],
                          ),

                          Padding(
                            padding: const EdgeInsets.fromLTRB(8, 8, 0, 8),
                            child: Text(
                              (cardBean.distance == null || cardBean.distance == 0)
                                  ? "距离未知"
                                  : "${cardBean.distance~/1000}km",
                              style: QuhuiConstant.smallTextBold,
                            ),
                          )
                        ],
                      ), //背景上面的其他组件
                    ),
                  ),
                ),
              )
            ],
          ),
        );
      },
    );

    cards.addAll(list);
    cardBeans.addAll(content);
  }
}
